package getVideo

import (
	"awang/aWeb/aWebModels/record"
	"awang/aWeb/aWebModels/videos"
	"awang/config/config"
	"awang/config/db"
	awangDb "awang/config/db"
	"awang/utils"
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

func GetVideos(c *gin.Context) {
	m_db := awangDb.Connect()
	my_videos := new([]videos.Video)
	page, _ := strconv.Atoi(c.Query("page"))
	m_db.Order("id desc").Offset(page * 8).Limit(8).Find(my_videos)
	c.JSON(200, my_videos)
}

func GetPathVideos(c *gin.Context) {
	ip := c.ClientIP()
	m_db := db.Connect()
	m_db.Create(&record.VisitTimes{Ip: ip})
	// c.String(http.StatusOK, getFiles("videos"))
	c.String(http.StatusOK, getFiles(config.VideoPath))
}

func getFiles(dirPth string) (files string) {
	dir, err := ioutil.ReadDir(dirPth)
	if err != nil {
		return "nil"
	}

	PthSep := string(os.PathSeparator)
	//suffix = strings.ToUpper(suffix) //忽略后缀匹配的大小写

	for _, fi := range dir {
		if fi.IsDir() {
		} else {
			files += dirPth + PthSep + fi.Name() + ","
		}
	}

	return files
}

func UploadVideo(c *gin.Context) {
	file, err := c.FormFile("video")

	if err != nil {
		c.String(http.StatusBadRequest, fmt.Sprintf("get form err: %s", err.Error()))
		return
	}

	filename := filepath.Base(file.Filename)
	var only_file_name string = filename
	filename_split := strings.Split(filename, ".")

	// 判断文件格式是否正确
	isAllow := config.TypeIsAllow(filename_split[len(filename_split)-1])
	if !isAllow {
		c.String(http.StatusBadRequest, fmt.Sprintf("type error"))
		return
	} else {
		// fmt.Println("type true.")
	}

	// 判断文件是否存在
	m_md5 := md5.New()
	file_data, _ := file.Open()
	defer file_data.Close()
	io.Copy(m_md5, file_data)
	file_md5 := hex.EncodeToString(m_md5.Sum(nil))
	m_db := db.Connect()
	find_record := &videos.Video{}
	m_db.Where("md5 = ?", file_md5).First(&find_record)
	if find_record.ID != 0 {
		c.String(http.StatusBadRequest, fmt.Sprintf("already has."))
		return
	}

	// 存储视频
	filename = filename_split[0] + "_" + strconv.FormatInt(time.Now().Unix(), 10) + "." + filename_split[len(filename_split)-1]
	urls := config.UserVideoPath + filename
	if err := c.SaveUploadedFile(file, urls); err != nil {
		c.String(http.StatusBadRequest, fmt.Sprintf("upload file err: %s", err.Error()))
		return
	}

	// 获得并存储照片
	image_name := filename_split[0] + "_" + strconv.FormatInt(time.Now().Unix(), 10) + ".jpeg"
	image_url := config.UserImagePath + image_name
	f, err := os.Create(image_url)
	if err != nil {
		c.String(http.StatusBadRequest, fmt.Sprintf("create pic err: %s", err.Error()))
		return
	} else {
		io.Copy(f, utils.GetFrame(urls, 1))
	}

	// 保存数据库
	up_video := videos.Video{Name: only_file_name, Urls: urls, Md5: file_md5, Size: strconv.FormatInt(file.Size, 10), Image: image_url}
	m_db.Create(&up_video)

	res_data, _ := json.Marshal(up_video)
	c.String(http.StatusOK, fmt.Sprintf("%s", res_data))
}

func GetVisitTimes(c *gin.Context) {
	m_db := db.Connect()
	var count int
	vts := []record.VisitTimes{}
	m_db.Find(&vts).Count(&count)

	// 将结果变更类型为切片
	allVisit, _ := json.Marshal(vts)
	tmp_var := new([]interface{})
	json.Unmarshal(allVisit, tmp_var)

	// 在第一项插入总数量
	*tmp_var = append(*tmp_var, 0)
	copy((*tmp_var)[1:], *tmp_var)
	(*tmp_var)[0] = "totle: " + strconv.Itoa(count)

	bak_mess, _ := json.Marshal(*tmp_var)
	c.String(http.StatusOK, fmt.Sprintf("%s", bak_mess))
}
